from django.shortcuts import render, HttpResponse
from django.views.generic import View, ListView, TemplateView
from django.contrib.auth.models import User, Group, Permission
from django.contrib.auth.hashers import make_password
from users.models import *
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import permission_required


# Create your views here.
# class UserListView(View):
#     def get(self, request):
#         user_list = User.objects.all()
#         return render(request, 'user_list.html', locals())
class UserListView(ListView):
    template_name = 'user_list.html'
    model = User
    paginate_by = 8

    # def get_context_data(self, **kwargs):
    #     context = super().get_context_data()
    #     print(context)
    #     return context
    def get_context_data(self, **kwargs):
        context = super(UserListView, self).get_context_data(**kwargs)
        context['page_range'] = self.page_range(context['paginator'])
        return context

    def page_range(self, paginator):
        # 接收当前URL里的page参数
        if self.request.GET.get('page') == None:
            page = 1
        else:
            page = self.request.GET.get('page')
        current_index = int(page)
        page_range = 5
        start = current_index - 2
        end = current_index + 3
        # 计算取出几页
        current_pages_num = end - start
        # 计算差几页
        add_pages_num = page_range - current_pages_num
        # 如果end是最大页数 取完了 后面也没有
        if end == paginator.num_pages + 1:
            start = start - add_pages_num
        else:
            # 如果取出页面不够5页  后面还有页面可取 就补齐
            if current_pages_num < page_range:
                end = end + add_pages_num
        # 最小start 从1
        if start < 1:
            start = 1
        # 最大就等于总页数
        if end > paginator.num_pages:
            end = paginator.num_pages + 1
        print(start)
        print(end)
        return range(start, end)


class TestDataView(View):
    def get(self, request):
        from faker import Faker
        for i in range(10):
            faker = Faker(locale='zh_CN')
            # 一多对一模型 操作两个模型类
            user = User()
            user.username = Faker().first_name()
            user.email = faker.email()
            user.password = make_password(123456)
            user.save()
            profile = Profile()
            profile.name_cn = faker.name()
            profile.phone = faker.phone_number()
            profile.wechat = faker.phone_number()
            profile.profile = user
            profile.save()
        return HttpResponse('添加测试数据')


class UserAddView(View):
    @method_decorator(permission_required('user_add', raise_exception=True))
    def get(self, request):
        return render(request, 'user_add.html')

    # template_name = 'user_add.html'

    def post(self, request):
        # print(request.POST)
        res = {'status': 0, 'msg': '添加用户成功'}
        try:
            user = User()
            user.username = request.POST.get('username')
            user.email = request.POST.get('email')
            user.password = make_password(request.POST.get('password'))
            user.save()
            profile = Profile()
            profile.name_cn = request.POST.get('name_cn')
            profile.wechat = request.POST.get('wechat')
            profile.phone = request.POST.get('phone')
            profile.profile = user
            profile.save()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '添加用户失败'}
        # return HttpResponse('接收添加用户数据')
        return JsonResponse(res)


class UserUpdateView(View):
    def get(self, request):
        user_obj = User.objects.get(id=request.GET.get('id'))
        return render(request, 'user_update.html', locals())

    def post(self, request):
        res = {'status': 0, 'msg': '更新用户成功'}
        try:
            # 更新需要查询找到这条数据  添加是直接添加 不需要查询
            user = User.objects.get(id=request.POST.get('id'))
            user.username = request.POST.get('username')
            user.email = request.POST.get('email')
            user.password = make_password(request.POST.get('password'))
            user.save()
            # 根据user对象对应找到profile对象数据
            try:
                # 如果之前用户扩展表信息有数据  就查询出对应数据对象
                profile = Profile.objects.get(profile=user)
            except Exception as e:
                print(e)
                # 之前没有添加用户扩展表信息  创建新的扩展信息对应
                profile = Profile()
            profile.name_cn = request.POST.get('name_cn')
            profile.wechat = request.POST.get('wechat')
            profile.phone = request.POST.get('phone')
            profile.profile = user
            profile.save()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '更新用户失败'}
        return JsonResponse(res)


class UserDeleteView(View):
    def get(self, request):
        res = {'status': 0, 'msg': '删除用户成功'}
        try:
            User.objects.get(id=request.GET.get('id')).delete()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '删除用户失败'}
        return JsonResponse(res)


class UserStatusView(View):
    def get(self, request):
        user = User.objects.get(id=request.GET.get('id'))
        # 查询当前用户状态
        res = {}
        res['status'] = 0
        # 当前状态为禁用
        if user.is_active == 0:
            # 修改启用
            user.is_active = 1
            status = '启用'
        else:
            # 修改为禁用
            user.is_active = 0
            status = '禁用'
        try:
            user.save()
        except Exception as e:
            print(e)
            res['status'] = 1
            res['msg'] = status + '用户失败'
        res['msg'] = status + '用户成功'
        return JsonResponse(res)


class GroupListView(View):
    def get(self, request):
        object_list = Group.objects.all()
        # user_list = User.objects.all()
        return render(request, 'group_list.html', locals())


class GroupAddView(ListView):
    template_name = 'group_add.html'
    model = User

    def post(self, request):
        # return HttpResponse('添加用户组数据')
        # 添加数据到group
        res = {'status': 0, 'msg': '添加用户组成功'}
        try:
            group = Group()
            group.name = request.POST.get('name')
            group.save()
            # group和用户的对应关系
            # 遍历收集到的用户id的列表
            for id in request.POST.getlist('group_user'):
                # 查询出用户对象，通过反向查询 关联添加多对多关系
                group.user_set.add(User.objects.get(id=id))
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '添加用户组失败'}
        return JsonResponse(res)


class GroupUpdateView(View):
    def get(self, request):
        group_obj = Group.objects.get(id=request.GET.get('id'))
        user_list = User.objects.all()
        return render(request, 'group_update.html', locals())

    def post(self, request):
        res = {'status': 0, 'msg': '更新用户组成功'}
        try:
            group = Group.objects.get(id=request.POST.get('id'))
            group.name = request.POST.get('name')
            group.save()
            # group和用户的对应关系
            # 如果之前已经添加关系 可以清楚多对多的关系
            group.user_set.clear()
            # 遍历收集到的用户id的列表
            for id in request.POST.getlist('group_user'):
                # 查询出用户对象，通过反向查询 关联添加多对多关系
                group.user_set.add(User.objects.get(id=id))
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '更新用户组失败'}
        return JsonResponse(res)


class GroupDeleteView(View):
    def get(self, request):
        res = {'status': 0, 'msg': '删除用户组成功'}
        group = Group.objects.get(id=request.GET.get('id'))
        # 如果用户组下面有用户  就不删除用户组
        # if group.user_set.all():
        #     return JsonResponse({'status':1,'msg':'用户组下面有用户不允许删除'})
        try:
            group.delete()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '删除用户组失败'}
        return JsonResponse(res)


class PermListView(ListView):
    template_name = 'perm_list.html'
    model = Permission

    def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.exclude(name__regex='[a-zA-z]')
        return queryset


class UserSetPermView(ListView):
    template_name = 'user_set_perm.html'
    model = Permission

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['user_obj'] = User.objects.get(id=self.request.GET.get('id'))
        return context

    def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.exclude(name__regex='[a-zA-z]')
        return queryset

    def post(self, request):
        res = {'status': 0, 'msg': '用户权限设置成功'}
        try:
            user = User.objects.get(id=request.POST.get('id'))
            user.user_permissions = request.POST.getlist('perm_list[]')
            user.save()
        except Exception as e:
            print(e)
            res = {'status': 1, 'msg': '用户权限设置失败'}
        return JsonResponse(res)
